package org.libl.web.servlet.admin;

import org.libl.domain.Admin;
import org.libl.service.admin.AdminService;
import org.libl.service.admin.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 管理员模块的登录servlet: 接收登录请求,判断用户名或者密码是否正确
 */
@WebServlet("/admin/AdminLoginController")
public class AdminLoginController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.获取登录页面提交的用户名和密码
        String nameForm  = request.getParameter("username");
        String pswForm  = request.getParameter("password");
        //2.调用service层的登录页面,判断用户名或者密码是否正确
        AdminService service = new AdminServiceImpl();
        Admin admin= service.login(nameForm, pswForm);
        //3.向浏览器响应数据
        if(admin!=null){
            //说明用户名和密码是正确的,登录成功
            //---需求: 下次访问login.jsp回显登录用户名
            Cookie cookie = new Cookie("loginName",admin.getUsername());
            cookie.setMaxAge(3600*24*7);
            response.addCookie(cookie);
            //--------------------------------------
            //3.1将用户信息存到session里面,在主页面回显管理员名称
            request.getSession().setAttribute("admin",admin);
            //重定向到主页面
            response.sendRedirect(request.getContextPath()+"/admin/main.jsp");
        }else{
            //说明用户名或者密码是错误的,登录失败
            //3.2在登录页面,显示失败信息,将错误信息存到request域对象,转发到login.jsp
            request.setAttribute("loginError","用户名或者密码错误");
            request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }
}
